#-------------------------------------------------------------------------------
# Name:        World
# Purpose:
#
# Author:      Pablo
#
# Created:     03/09/2013
# Copyright:   (c) Monxcleyr Productions 2013
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, os, logging, random
import imagehandler, objecthandler, computer, dialog

class World():

  """World class handles the entire world, and functions as a save file. This instance, in
  lib/game/ will act as the default save, and when New Game is selected, this will be loaded."""

  def __init__(self, common):
    self.imagehandler = imagehandler.ImageHandler()
    self.objecthandler = objecthandler.ObjectHandler(self.imagehandler)
    self.version = common.version

    # How many frames left to shake!
    self.shakecount = 0

    # these are loaded and shown on the save screen. They can be basically anything
    self.savename = 'New Game'
    self.detail = 'Introduction'

    # How long the game has been playing, in seconds, including minigame time
    self.timeplayed = 0

    # How long the game has been playing, in seconds, excluding minigame time
    self.gametime = 0

    self.dialog = dialog.Dialog(common, self.imagehandler)
    self.dialog.loadScript()

    self.computer = computer.Computer(self.dialog)


  def testDialog(self):

    self.dialog.addDialog('traditional', ' ', (100,100), [1], 'test', False)
    self.dialog.getDialogByName('test').loadText('test.txt')



  def updateOffset(self, screen, sound, settings):

    """ Calculates and updates the camera offset to keep the player centered. """

    pos = self.objecthandler.getObjectByType('player').attributes['pos']
    screensize = (screen.get_width() / 2, screen.get_height() / 2)

    self.offset = (int(screensize[0] - pos[0]), int(screensize[1] - pos[1]))

    if self.computer.failedtask:
      self.computer.failedtask = False
      self.shakecount = 20
      sound.play('explosion', settings)
    if self.shakecount != 0:
      self.shake()



  def shake(self):

    """ SHAKE DAT SCREEN, YO! """

    shake = (random.randint(-4,4), random.randint(-4,4))
    self.offset = (self.offset[0] + shake[0], self.offset[1] + shake[1])
    self.shakecount -= 1





  def updateCollisions(self, obj):

    """ Update collisions between given object and ship. """

    for tile in self.objecthandler.getObjectByType('ship').attributes['tiles']:
      if obj.getRect().colliderect(tile.getRect()):
        self.satCollision(obj, tile)

    for col_obj in self.objecthandler.objects:
      if 'solid' in col_obj.attributes and col_obj.type != 'player':
        if col_obj.attributes['solid'] == True and col_obj.attributes['visable']:
          if col_obj.getBoundingRect().colliderect(obj.getRect()):
            self.spriteCollision(obj, col_obj)



#-------------------------------------------------------------------------------


  def satCollision(self, entity, tile):

    """ This calculates the actual collisions between two rects. """

    x1 = entity.attributes['pos'][0]
    y1 = entity.attributes['pos'][1]
    w1 = entity.getRect().width
    h1 = entity.getRect().height
    x2 = tile.attributes['pos'][0] + tile.attributes['parent'].attributes['pos'][0]
    y2 = tile.attributes['pos'][1] + tile.attributes['parent'].attributes['pos'][1]
    h2 = tile.getRect().height
    w2 = tile.getRect().width
    project = []

    if x1 + w1 > x2 + w2:
      dx = x1 + w1 - x2
      project.append('left')
    else:
      dx = x2 + w2 - x1
      project.append('right')
    if y1 + h1 > y2 + h2:
      dy = y1 + h1 - y2
      project.append('up')
    else:
      dy = y2 + h2 - y1
      project.append('down')
    if abs(dx) > abs(dy):
      if project[0] == 'left':
        entity.attributes['pos'] = (x2 + w2, entity.attributes['pos'][1])
      else:
        entity.attributes['pos'] = (x2 - w1, entity.attributes['pos'][1])
    if abs(dx) <= abs(dy):
      if project[1] == 'down':
        entity.attributes['pos'] = (entity.attributes['pos'][0], y2 - h1)
      else:
        entity.attributes['pos'] = (entity.attributes['pos'][0], y2 + h2)


  def spriteCollision(self, entity, sprite):

    """ This calculates the actual collisions between two rects. """

    x1 = entity.attributes['pos'][0]
    y1 = entity.attributes['pos'][1]
    w1 = entity.getRect().width
    h1 = entity.getRect().height
    x2 = sprite.getBoundingRect().left
    y2 = sprite.getBoundingRect().top
    h2 = sprite.getBoundingRect().height
    w2 = sprite.getBoundingRect().width
    project = []

    if x1 + w1 > x2 + w2:
      dx = x1 + w1 - x2
      project.append('left')
    else:
      dx = x2 + w2 - x1
      project.append('right')
    if y1 + h1 > y2 + h2:
      dy = y1 + h1 - y2
      project.append('up')
    else:
      dy = y2 + h2 - y1
      project.append('down')
    if abs(dx) > abs(dy):
      if project[0] == 'left':
        entity.attributes['pos'] = (x2 + w2, entity.attributes['pos'][1])
      else:
        entity.attributes['pos'] = (x2 - w1, entity.attributes['pos'][1])
    if abs(dx) <= abs(dy):
      if project[1] == 'down':
        entity.attributes['pos'] = (entity.attributes['pos'][0], y2 - h1)
      else:
        entity.attributes['pos'] = (entity.attributes['pos'][0], y2 + h2)

